{

  Radioloop
  v 1.0
  A simple object to sample the pulsewidth-- probably from an RC reciever.
  You can always find out the last sample.

  Next steps:
        Add averaging
        Add more channels
}
    

VAR
  long nval[3]
  long current[3]
  long rpin[3]
  long stack[256]


PUB Init(pinin_a, pinin_b, pinin_c)
  rpin[0]:=pinin_a
  rpin[1]:=pinin_b
  rpin[2]:=pinin_c
  cognew(MainLoop, @stack)
                               
PUB MainLoop | loop
  repeat
    repeat loop from 0 to 2
      nval:=PULSIN(rpin[loop],1)    ' If the pulse doesn't come, this is frozen
      current[loop]:=nval
    
PUB SetNext(num, n)
  current[num]:=n


' Get Current pulse width
' DON'T GetCurrent WHILE DOING THE CONNECTED TEST  
PUB GetCurrent(n)
  return current[n]

{
  TEST CONNECTION
  Start connection test.  Wait 
}
PUB StartConnectedTest
  SetNext(0, 5000)
  
PUB IsConnected
  return (GetCurrent(0)<>5000)
PUB PULSIN (Pin, PState) : Duration | us
{{ From BS2 Functions Library Object

   Reads duration of Pulse on pin defined for state, returns duration in 2uS resolution
   Shortest measureable pulse is around 20uS
   Note: Absence of pulse can cause cog lockup if watchdog is not used - See distributed example
    x := BS2.Pulsin(5,1)
    BS2.Debug_Dec(x)
}}
   us :=   clkfreq / 1_000_000                  ' Clock cycles for 1 us
    
   Duration := PULSIN_Clk(Pin, PState) / us / 2 + 1         ' Use PulsinClk and calc for 2uS increments \

PUB PULSIN_Clk(Pin, PState) : Duration 
{{ From BS2 Functions Library Object; modified waitpne and waitpeq functions to use |< Pin

   Reads duration of Pulse on pin defined for state, returns duration in 1/clkFreq increments - 12.5nS at 80MHz
   Note: Absence of pulse can cause cog lockup if watchdog is not used - See distributed example
    x := BS2.Pulsin_Clk(5,1)
    BS2.Debug_Dec(x)
}}

  DIRA[pin]~
  ctra := 0
  if Pstate == 1
    ctra := (%11010 << 26 ) | (%001 << 23) | (0 << 9) | (PIN) ' set up counter, A level count
  else
    ctra := (%10101 << 26 ) | (%001 << 23) | (0 << 9) | (PIN) ' set up counter, !A level count
  frqa := 1
  waitpne(|< Pin, |< Pin, 0)                         ' Wait for opposite state ready
  phsa:=0                                                  ' Clear count
  waitpeq(|< Pin, |< Pin, 0)                         ' wait for pulse
  waitpne(|< Pin, |< Pin, 0)                         ' Wait for pulse to end
  Duration := phsa                                         ' Return duration as counts
  ctra :=0    